"""
初始化订单账号数据库
"""
import json
import os
from .models import OrderAccount
from .sqlalchemy_database import SQLAlchemyDatabaseManager

def import_order_account_data():
    """
    导入order_account_data.json数据到数据库
    """
    db = SQLAlchemyDatabaseManager()
    session = db.get_session()
    
    try:
        # 获取数据文件路径
        current_dir = os.path.dirname(os.path.abspath(__file__))
        data_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(current_dir))), "data")
        json_file = os.path.join(data_dir, "order_account_data.json")
        
        if not os.path.exists(json_file):
            print(f"订单账号数据文件不存在: {json_file}")
            return
            
        # 读取JSON数据
        with open(json_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
            
        # 导入数据
        for item in data:
            account = OrderAccount(
                name=item['name'],
                tags=item.get('tags'),
                uu_token=item.get('uu_token'),
                device_id=item.get('device_id'),
                alive=item.get('alive', 0),
                status=item.get('status', 1),
                locked=item.get('locked', 0),
                locked_at=item.get('locked_at', 0),
                safe_verify=item.get('safe_verify', 0),
                uu_user_id=item.get('uu_user_id'),
                avatar=item.get('avatar'),
                nickname=item.get('nickname'),
                invalid_desc=item.get('invalid_desc'),
                steam_id=item.get('steam_id'),
                min_interval=item.get('min_interval', 10),
                create_at=item.get('create_at'),
                update_at=item.get('update_at'),
                alive_times=item.get('alive_times', 0)
            )
            session.add(account)
            
        session.commit()
        print("订单账号数据导入成功")
        
    except Exception as e:
        session.rollback()
        print(f"导入订单账号数据时发生错误: {str(e)}")
    finally:
        session.close()

if __name__ == "__main__":
    import_order_account_data()
